﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Globalization;
using IntroduceCompany.Util;
using System.Web.Security;

namespace IntroduceCompany
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //routes.IgnoreRoute("{resource}.axpx/{*pathInfo}");

            routes.MapRoute(
                "Default2", // Route name
                "", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

            routes.MapRoute(
                "Frontend_NewProductList",
                "npr/{productTypeSEO_URL}",
                new { controller = "Product", action = "ProductListFrontend" }, new { productTypeSEO_URL = @"[a-zA-Z0-9-]{1,}" }
            );

            routes.MapRoute(
                "Frontend_ProductList",
                "pr/{productTypeSEO_URL}/{pageIndex}",
                new { controller = "Product", action = "ProductList", productTypeSEO_URL = "", pageIndex = "1" }, 
                new { productTypeSEO_URL = @"[a-zA-Z0-9-]{1,}", pageIndex = @"[0-9-]{1,}" }
            );

            routes.MapRoute(
                "Frontend_ProductDetails",
                "prDe/{productTypeSEO_URL}/{productSeo_URL}",
                new { controller = "Product", action = "ProductDetails", productSeo_URL = "" },
                new { productSeo_URL = @"[a-zA-Z0-9-]{1,}" }
            );

            routes.MapRoute(
                "Frontend_SurveyPage",
                "sur/{menuTypeSEO_URL}",
                new { controller = "Survey", action = "SurveyPage", menuTypeSEO_URL = "" },
                new { menuTypeSEO_URL = @"[a-zA-Z0-9-]{1,}" }
            );

            routes.MapRoute(
                "Frontend_ArticleDetails", // Route name
                "artDe/{articleTypeSEO_URL}/{articleSEO_URL}", // URL with parameters
                new { controller = "Article", action = "Frontend_ArticleDetails", articleSEO_URL = "" },
                new { articleSEO_URL = @"[a-zA-Z0-9-]{1,}" } // Parameter defaults
            );

            routes.MapRoute(
                "Frontend_ArticleList",
                "art/{articleTypeSEO_URL}/{pageIndex}",
                new { controller = "Article", action = "Frontend_ArticleList", articleTypeSEO_URL = "", pageIndex = "1" }, 
                new { articleTypeSEO_URL = @"[a-zA-Z0-9-]{1,}", pageIndex = @"[0-9-]{1,}" }
            );

            routes.MapRoute(
                "Frontend_AlbumList", // Route name
                "alb/{albumMenu_SEO_URL}/{pageIndex}", // URL with parameters
                new { controller = "Album", action = "Frontend_AlbumList",albumMenu_SEO_URL="", pageIndex = "1" },
                new { albumMenu_SEO_URL = @"[a-zA-Z0-9-]{1,}", pageIndex = @"[0-9-]{1,}" } 
            );

            routes.MapRoute(
                "Frontend_AlbumDetails", // Route name
                "albde/{albumMenu_SEO_URL}/{album_SEO_URL}", // URL with parameters
                new { controller = "Album", action = "Frontend_AlbumDetails", album_SEO_URL = "", albumMenu_SEO_URL =""},
                new { album_SEO_URL = @"[a-zA-Z0-9-]{1,}", albumMenu_SEO_URL = @"[a-zA-Z0-9-]{1,}" } // Parameter defaults
            );

            routes.MapRoute(
                "Frontend_Video_Route",
                "vid/{videoMenu_SEO_URL}/{pageIndex}/{video_SEO_URL}",
                new { controller = "Video", action = "Frontend_VideoList", video_SEO_URL = "", pageIndex = "1", videoMenu_SEO_URL="" },
                new { video_SEO_URL = @"^[a-zA-Z0-9-]{0,}$", videoMenu_SEO_URL = @"^[a-zA-Z0-9-]{0,}$", pageIndex = @"[0-9-]{1,}" } 
            );

            routes.MapRoute(
                "Frontend_Feedback_Route",
                "Feedback",
                new { controller = "Feedback", action = "Frontend_FeedbackCreate" }
            );

            routes.MapRoute(
            "Frontend_Cart",
            "Cart",
            new { controller = "Order", action = "ViewCart" }
            );

            routes.MapRoute(
            "Frontend_Order",
            "Order",
            new { controller = "Order", action = "CreateOrder" }
            );

            routes.MapRoute(
            "Frontend_Error404",
            "Error404",
            new { controller = "Error", action = "Error404" }
            );

            routes.MapRoute(
            "Frontend_Error",
            "Error",
            new { controller = "Error", action = "Error" }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );



            var lang_arr = new List<string> { };
            IQueryable<Language> lang_list =  IntroduceCompany.Singleton.DataSingleton.GetInstance().Languages;
            foreach (var item in lang_list)
            {
                lang_arr.Add(item.LanguageID);
            }

            foreach (Route r in routes)
            {
                if (!(r.RouteHandler is SingleCultureMvcRouteHandler))
                {
                    r.RouteHandler = new MultiCultureMvcRouteHandler();
                    r.Url = "{culture}/" + r.Url;
                    //Adding default culture 
                    if (r.Defaults == null)
                    {
                        r.Defaults = new RouteValueDictionary();
                    }
                    r.Defaults.Add("culture", ConstantClass.mainLanguageID);

                    //Adding constraint for culture param
                    if (r.Constraints == null)
                    {
                        r.Constraints = new RouteValueDictionary();
                    }
                    r.Constraints.Add("culture", new CultureConstraint(lang_arr.ToArray()));
                }
            }
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (Context.User != null)
            {
                string cookieName = FormsAuthentication.FormsCookieName;
                HttpCookie authCookie = Context.Request.Cookies[cookieName];
                if (authCookie == null)
                    return;

                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                string[] roles = authTicket.UserData.Split(new char[] { '|' });

                //We create a new generic principal based on the roles we defined in the cookie.
                //See SetAuthenticationCookie in AuthenticationService
                FormsIdentity fi = (FormsIdentity)(Context.User.Identity);
                Context.User = new System.Security.Principal.GenericPrincipal(fi, roles);
            }
        }
    }
}